package com.fauks.gmall.cart.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.fauks.gmall.annotation.LoginRequired;
import com.fauks.gmall.bean.OmsCartItem;
import com.fauks.gmall.bean.PmsSkuInfo;
import com.fauks.gmall.service.CartService;
import com.fauks.gmall.service.SkuService;
import com.fauks.gmall.util.CookieUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
public class CartController {

    @Reference
    private SkuService skuService;

    @Reference
    private CartService cartService;

    @LoginRequired(isNeedLogin = true)
    @RequestMapping("toTrade")
    public String toTrade() {
        return "toTrade";
    }

    @LoginRequired(isNeedLogin = false)
    @RequestMapping("cartList")
    public String cartList(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
        String memberId = "2";
        List<OmsCartItem> cartList;
        if (StringUtils.isEmpty(memberId)) {
            //用户未登录，从cookie中取购物车数据
            String cartListCookie = CookieUtil.getCookieValue(request, "cartListCookie", true);
            cartList = JSON.parseArray(cartListCookie, OmsCartItem.class);
        } else {
            //用户已存在从缓存中取数据
            cartList = cartService.cartList(memberId);
        }
        modelMap.put("cartList", cartList);
        return "cartList";
    }

    @RequestMapping("addToCart")
    public String addToCart(String skuId, int quantity, HttpServletRequest request, HttpServletResponse response) {
        List<OmsCartItem> cartItemList = new ArrayList<>();
        //获取当前sku详情
        PmsSkuInfo skuInfo = skuService.getSkuById(skuId, "");
        OmsCartItem newCartItem = new OmsCartItem();
        //封装购物车信息
        newCartItem.setCreateDate(new Date());
        newCartItem.setDeleteStatus(0);
        newCartItem.setPrice(skuInfo.getPrice());
        newCartItem.setProductId(skuInfo.getProductId());
        newCartItem.setModifyDate(new Date());
        newCartItem.setProductName(skuInfo.getSkuName());
        newCartItem.setProductSkuId(skuId);
        newCartItem.setQuantity(new BigDecimal(quantity));

        String memberId = "2";
        if (StringUtils.isEmpty(memberId)) {
            String cookieName = "cartListCookie";
            //用户未登录将购物车数据存入cookie
            String oldCartListStr = CookieUtil.getCookieValue(request, cookieName, true);
            if (StringUtils.isEmpty(oldCartListStr)) {
                //cookie中没有购物车数据则存入
                newCartItem.setTotalPrice(newCartItem.getPrice().multiply(new BigDecimal(quantity)));
                cartItemList.add(newCartItem);
            } else {
                cartItemList = JSON.parseArray(oldCartListStr, OmsCartItem.class);
                //更新购物车
                boolean isSkuExists = is_cart_exists(newCartItem, cartItemList);
                if (isSkuExists) {
                    //购物车已存在商品则更新数量
                    for (OmsCartItem cartItem : cartItemList) {
                        if (cartItem.getProductSkuId().equals(newCartItem.getProductSkuId())) {
                            cartItem.setQuantity(cartItem.getQuantity().add(new BigDecimal(quantity)));
                        }
                    }
                } else {
                    //添加新商品直接加入
                    cartItemList.add(newCartItem);
                }
            }
            CookieUtil.setCookie(request, response, cookieName, JSON.toJSONString(cartItemList), 60 * 60 * 24 * 3, true);

            List<OmsCartItem> printCart = JSON.parseArray(CookieUtil.getCookieValue(request, cookieName, true), OmsCartItem.class);
            if (printCart != null) {
                StringBuilder sb = new StringBuilder("【测试购物车添加到cookie】")
                        .append("\n");
                for (OmsCartItem cartItem : printCart) {
                    sb.append("【商品名称：】")
                            .append(cartItem.getProductName())
                            .append("【数量】")
                            .append(cartItem.getQuantity())
                            .append("\n");
                }
                System.out.println(sb.toString());
            } else {
                System.out.println("cookie中无数据");
            }
        } else {
            //已登录存入数据库
            OmsCartItem cartItemByDb = cartService.cartExistsInDbByMember(skuId, memberId);
            if (cartItemByDb == null) {
                //新添加的商品直接入库
                newCartItem.setMemberId(memberId);
                newCartItem.setMemberNickname("slx");
                cartService.saveCartItem(newCartItem);
            } else {
                //商品已存在更新数量
                cartItemByDb.setQuantity(cartItemByDb.getQuantity().add(new BigDecimal(quantity)));
                cartService.updateCartItem(cartItemByDb);
            }
            //刷新缓存
            cartService.flushCartCache(memberId);
        }
        return "redirect:/success.html";
    }

    //判断要加入购物车的商品在购物车中是否存在
    private boolean is_cart_exists(OmsCartItem newCartItem, List<OmsCartItem> cartItemList) {
        boolean isExists = false;
        for (OmsCartItem cartItem : cartItemList) {
            if (cartItem.getProductSkuId().equals(newCartItem.getProductSkuId())) {
                isExists = true;
                break;
            }
        }
        return isExists;
    }
}
